import {
  getImage,
  getPage,
  getTabbar
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
const app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  console.log(headerInfo)
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getImage: getImage,
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    navbar: {},
    window: {},
    hfListIndex: 0,
    botZtListIndex: 0,
    timesHours: 0,
    guize: {},
    city: "",
    timesMinute: 0,
    timesSecond: 0,
    goodsNavFix: false,
    goodsNavType: 1,
    goodsList: [],
    goodsListPage: 1,
    goodsListPages: 0,
    loadmore: true,
    loaddone: false,
    popupShow: false,
    popupShow1: false,
    popupShowTip: false,
    showwellcome: false,
    tipTopStyle: tipTopStyle,
    leftStyle: leftStyle,
    topStyle: topStyle,
    imgheights: {},
    imgheightsUser: {},
    curBannerHeight: 0,
    value1: 0,
    option1: [],
    cid: 0,
    crossAxisCount: 2,
    crossAxisGap: 8,
    mainAxisGap: 8,
    myTime:null,
    tabsActive:'推荐',
    orders:1
  },
  tabsClick(e){
    let tit = e.detail.title;
    this.setData({
      tabsActive:tit,
      orders:tit=='推荐'?1:''
    })
    this.getProductsInfo((res) => {
      this.setData({
        goodsList: res.list,
        loadmore: false,
      });
    });
  },
  goxuqiu(){
    wxApi.navigateTo(getPage.myxuqiu);
  },
  gosheji() {
    wxApi.redirectTo('/pages/designer/home');
  },
  handleNotouch() {
    return false
  },
  goxuqiudetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.xuqiudetail, {
        id: data.id
      });
    }
  },
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  imageLoadUser: function (e) { //获取图片真实宽度 
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    let bol = ratio>1? true :false
    var imgheightsUser = this.data.imgheightsUser;
    imgheightsUser[e.target.dataset.id] = bol;
    this.setData({
      imgheightsUser: imgheightsUser
    })
    // console.log('imgheightsUser',imgheightsUser)
  },
  updateDot(data){
    let dots = data.detail.dots;
    this.setData({ dots })
  },

  mesClick(e) {
    wxApi.navigateTo("/pages/location/index");
  },

  /**
   * swiper 记录当前值
   */
  hfListChange(e) {
    this.setData({
      hfListIndex: e.detail.current
    })
  },

  botZtListChange(e) {
    this.setData({
      botZtListIndex: e.detail.current
    })
  },

  /**
   * 搜索
   */
  visitSearch() {
    wxApi.navigateTo(getPage.searchfabu);
  },

  golink(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    console.log(data.url);
    //转为小写并去除左右空格
    var str = data.url.toLowerCase();
    if (str != "") {
      if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
        wxApi.navigateTo("/pages/web/web?id=" + str);
      } else if (str.indexOf('za://') == 0) {
        console.log(str);
        var array = str.split('_');
        console.log(array);
        if (array[0].replace("za://", "") == 'column') {
          app.g_cid = array[1];
          wx.switchTab({
            url: getPage.column
          });
        }
      } else {
        wxApi.navigateTo("/pages/goods/goods?id=" + str);
      }
    }
  },
  /**
   * 禁止手动滑动
   */
  noSwiping() {
    return false;
  },
  oncategorychange(e) {
    this.setData({
      cid: e.detail,
      goodsListPage: 1
    });
    //加载产品列表
    this.getProductsInfo((res) => {
      console.log(res)
      this.setData({
        goodsList: res.list,
        loadmore: false,

      });
    });
  },
  /**
   * 获取产品数据
   */
  getProductsInfo(cb, a = false) {
    let {
      goodsNavType,
      goodsListPage,
      goodsListPages,
      cid,
      loaddone,
      userId,
      orders
    } = this.data;
    var latitude = 0,
      longitude = 0;
    var mylocation = null;
    if (wx.getStorageSync('mylocation') == "" && app.globalData.zone == null) {
      wxApi.navigateTo("/pages/location/index");
      return;
    } else if (wx.getStorageSync('mylocation') != "") {
      mylocation = JSON.parse(wx.getStorageSync('mylocation'));
      latitude = mylocation.latitude;
      longitude = mylocation.longitude;
    } else {
      latitude = app.globalData.zone.lat;
      longitude = app.globalData.zone.lng;
    }
    http.post(api.default, {
      data: {
        action: 'getxuqiulist',
        userid:userId,
        pagesize: 20,
        pageindex: goodsListPage, 
        cid: cid,
        latitude: latitude,
        longitude: longitude,
        orders
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      if (goodsListPage == data.pages) loaddone = true;
      this.setData({
        goodsListPages: data.pages,
        loaddone,
      });
      cb && cb(data);
    });
  },
  fabu() {
    wxApi.navigateTo(getPage.fabuxuqiu);
  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    if (this.data.city == "")
      this.setData({
        city: app.globalData.zone.shortname,
      })
    //第一部分数据加载
    http.post(api.default, {
      data: {
        action: 'getadsbanner',
        type: 6
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      console.log(res.data);
      this.setData({
        swiper: data,
        loading: 1
      });
    });
    http.post(api.default, {
      data: {
        action: 'getcategoryoption'
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      //console.log(res.data);
      this.setData({
        option1: res.data.data
      });
    });
    setTimeout(() => {
      //加载产品列表
      this.getProductsInfo((res) => {
        console.log(res)
        this.setData({
          goodsList: res.list,
          loadmore: false,
        });
      });
    }, 1);
  },

  /**
   * 页面滚动函数--监听页面滚动事件
   */
  onPageScroll(e) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //获取用户登录
    app.getLogin().then((res) => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id,
        logged: res.code,
      })
      this.getunreadmsg();
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      // this.goLogin();
    })
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        // 这里的数字对应tabbar对应的索引
        selected: 2,
        v_count: app.globalData.v_count
      });
      console.log('this.getTabBar()',this.getTabBar())
      let getTabBar = this.getTabBar();
      getTabBar.setData({
        number:app.globalData.unReadMsg
      });
      this.setData({
        myTime:setInterval(function(){
          // console.log('getTabBar',getTabBar)
          getTabBar.setData({
            number:app.globalData.unReadMsg
          });
        },5000)
      })
    }
  },

  // 获取未读消息数
  getunreadmsg() {
    http.post(api.default, {
      data: {
        action: 'getmsgcount',
        userid: this.data.userId
      }
    }, false).then(res => {
      let {
        data
      } = res.data;
      let unReadMsg = data.msgcount + data.fw_notice + data.sys_notice
      app.globalData.unReadMsg = unReadMsg;
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          number: app.globalData.unReadMsg,
        });
      }
    })
  },

  /**
   * 关注店铺
   */
  followClick(event) {
    let {
      xqid
    } = event.currentTarget.dataset
    var {
      logged,
      userId,
    } = this.data;
    console.log('logged',logged)
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'like_xuqiu',
          userid: userId,
          id: xqid,
        }
      }).then((res) => {
        let {errmsg,data} = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // 前端显示跟新收藏状态
        let goodsArr = this.data.goodsList;
        goodsArr.forEach(item => {
          if (item.id == xqid) {
            item.is_like = data,
            item.likes_num = data?item.likes_num+1:item.likes_num-1
          }
        })
        this.setData({
          goodsList: goodsArr
        })
      })
    } else {
      this.goLogin();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('user_onHide________清除定时器~')
    clearInterval(this.data.myTime);
    wx.closeSocket()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.closeSocket()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: '加载中...',
    })
    this.setData({
      goodsListPage:1
    })
    //加载产品列表
    this.getProductsInfo((res) => {
      console.log(res)
      this.setData({
        goodsList: res.list,
        loadmore: false,
      });
      wx.stopPullDownRefresh();
      wx.hideLoading();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      goodsListPage,
      goodsListPages,
      loadmore
    } = this.data;
    //未请求完且未在加载中
    if (goodsListPages > goodsListPage && !loadmore) {
      goodsListPage++;
      loadmore = true;

      //显示加载效果
      this.setData({
        goodsListPage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.getProductsInfo((res) => {
        let {
          goodsList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          goodsList: goodsList.concat(res.list),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})